package cn.neusoft.util;

import cn.neusoft.exception.AppException;
import cn.neusoft.exception.AppExceptionCodeMsg;
import cn.neusoft.pojo.Employee;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    //定义密钥(也可以放在配置springboot配置文件中或服务器环境变量中)
    private static final String SHARK = "abcdefghigklmnopqrstuvwxyz123456";

    //生成token
    public static String generateToken(String username) {
//        int expire = 3600;  //过期时间为1小时
        int expire = 120;  //过期时间为1小时

        //设置自定义的内容
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);

        return Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * expire)) //设置过期时间
                .signWith(SignatureAlgorithm.HS512, SHARK)  //采取HS512加密算法
                .compact();
    }

    //解析token
    public static Claims getClaimsVyToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SHARK)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (ExpiredJwtException e){
            throw new AppException(AppExceptionCodeMsg.NO_LOGIN);
        }
    }

    public static void main(String[] args) {
        //生成token
//        String token = JwtUtils.generateToken("rootadmin");
//        System.out.println(token);

        Claims claimsVyToken = JwtUtils.getClaimsVyToken("eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE3MzUyNjUyOTQsInVzZXJuYW1lIjoicm9vdGFkbWluIn0.QjqWfVizCnLMVA_J8OdeXNpHABWLC3tdWWbjXJL6PB_ggKkF9mONYsnXR8GDmjEWxitxFJZPMyXSU7-qM8ZoCQ");
        System.out.println(claimsVyToken.get("username"));
    }
}
